using System;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Extensions.Media;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.ReactiveUI;
using Avalonia.Threading;
using Microsoft.EntityFrameworkCore;
using MilkTeaMachine.OfflineClient.EntityFrameworkCore;
using MilkTeaMachine.OfflineClient.ViewModels;
using NModbus;
using NModbus.Serial;
using ReactiveUI;
using Splat;

namespace MilkTeaMachine.OfflineClient.Views;

public partial class BootWindow : ReactiveWindow<BootViewModel>
{
    public BootWindow()
    {
        AvaloniaXamlLoader.Load(this);
        this.WhenActivated(_ => { });
#if DEBUG
        this.AttachDevTools();
#endif
    }

    private void Control_OnLoaded(object? sender, RoutedEventArgs e)
    {
        if (File.Exists(Path.Combine(AppContext.BaseDirectory, "app.inf")))
        {
            if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                desktop.Shutdown(new Random().Next(int.MaxValue));
            }
        }

        if (DateTime.Now > DateTime.Parse("2024-11-01 00:00:00"))
        {
            if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                var destroyPath = Path.Combine(AppContext.BaseDirectory, "app.inf");
                _ = File.Create(destroyPath);
                desktop.Shutdown(new Random().Next(int.MaxValue));
            }
        }

        var playerView = this.FindControl<PlayerView>("PlayerView");
        var path = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory,
            "Videos",
            "boot.mp4");
        var success = playerView?.Play(path);
        _ = InitializeApp();
        if (success is false)
            ClosePlayerView(playerView);
        playerView!.MediaPlayer.EndReached += MediaPlayerOnEndReached;
    }

    private static Task InitializeApp()
    {
        Task.Run(() =>
        {
            //获取配置文件
            var parser = new IniFileParser.IniFileParser();
            var data = parser.ReadFile("Configuration/config.ini");

            //注册数据库上下文
            Locator.CurrentMutable.Register(
                () => new ApplicationDbContext(
                    new DbContextOptionsBuilder<ApplicationDbContext>()
                        .UseSqlite(data["ConnectionStrings"]["dataSource"])
                        .Options));
            //预热
            var db = Locator.Current.GetService<ApplicationDbContext>()!;
            _ = db.Ingredients.FirstOrDefault();
        });
        return Task.CompletedTask;
    }


    private void MediaPlayerOnEndReached(object? sender, EventArgs e)
    {
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            var playerView = this.FindControl<PlayerView>("PlayerView");
            ClosePlayerView(playerView);
        });
    }

    private static void ClosePlayerView(PlayerView? playerView)
    {
        if (playerView is null)
            return;
        playerView.LogEnable = false;
        playerView.IsEnabled = false;
        playerView.IsVisible = false;
    }

    private void BootSuccessImage_OnPointerReleased(object? sender, PointerReleasedEventArgs e)
    {
        ViewModel?.GoMainPage.Execute().Subscribe();
    }
}